﻿@using System.ComponentModel.DataAnnotations
@using Deploy.DataTransmitModel.DefaultData
@using Deploy.Enums
@using Deploy.HttpManage
@using Deploy.PresentationModel.DefaultData
@using Materal.APP.Core.Models
@using WebAPP.MateralUI.Models
@using Materal.Model
@using Materal.Common
@using WebAPP.Common


@inject MessageManage _messageManage
@inject ExceptionManage _exceptionManage
@inject IDefaultDataManage _defaultDataManage

<section>
    <MForm @ref="@Form" FromData="@FormData">
        <MFormItem Title="键" PropertyModel="@context.Key" IsRequired>
            <MInput Type="text" Disabled="@Loading" @bind-Value="@context.Key.Value"></MInput>
        </MFormItem>
        <MFormItem Title="应用类型">
            <MSelect Disabled="@Loading" Items="AllApplicationTypes" @bind-Value="@context.ApplicationType"></MSelect>
        </MFormItem>
        <MFormItem Title="数据" PropertyModel="@context.Data" IsRequired>
            <MInput Type="text" Rows="6" Disabled="@Loading" OnInputChange="OnDataChanged" @bind-Value="@context.Data.Value"></MInput>
        </MFormItem>
    </MForm>
    <div class="m_modal_buttons">
        <MButton Disabled="@Loading" OnClick="@OnBtnCancelClickAsync">取消</MButton>
        <MButton ButtonType="@MButtonTypeEnum.Primary" Disabled="@Loading" OnClick="@OnBtnSaveClickAsync">确定</MButton>
    </div>
</section>

@code{
    /// <summary>
    /// 操作默认数据表单数据模型
    /// </summary>
    public class OperationDefaultDataFromDataModel
    {
        /// <summary>
        /// 键
        /// </summary>
        [Required(ErrorMessage = "键不能为空"), StringLength(100, ErrorMessage = "键长度不能超过100")]
        public FromDataPropertyModel<string> Key { get; set; } = new FromDataPropertyModel<string>();
        /// <summary>
        /// 数据
        /// </summary>
        [Required(ErrorMessage = "数据不能为空")]
        public FromDataPropertyModel<string> Data { get; set; } = new FromDataPropertyModel<string>();
        /// <summary>
        /// 应用程序类型
        /// </summary>
        public KeyValueModel ApplicationType { get; set; } = new KeyValueModel(ApplicationTypeEnum.DotNetCore);
    }
}
@code {
    #region 参数
    /// <summary>
    /// 所有应用程序类型
    /// </summary>
    public List<KeyValueModel> AllApplicationTypes { get; set; }
    /// <summary>
    /// 默认数据唯一标识
    /// </summary>
    [Parameter]
    public Guid? DefaultDataID { get; set; }
    /// <summary>
    /// 成功
    /// </summary>
    [Parameter]
    public EventCallback Success { get; set; }
    /// <summary>
    /// 取消
    /// </summary>
    [Parameter]
    public EventCallback Cancel { get; set; }
    #endregion
    #region 属性字段
    /// <summary>
    /// 加载状态
    /// </summary>
    public bool Loading { get; set; } = true;
    /// <summary>
    /// 窗体
    /// </summary>
    public MForm<OperationDefaultDataFromDataModel> Form { get; set; }
    /// <summary>
    /// 表单数据
    /// </summary>
    public OperationDefaultDataFromDataModel FormData = new OperationDefaultDataFromDataModel();

    private Guid? _upInitDefaultDataID;

    #endregion
    #region 生命周期
    /// <summary>
    /// 设置参数后
    /// </summary>
    /// <returns></returns>
    protected override async Task OnParametersSetAsync()
    {
        AllApplicationTypes = KeyValueModel.GetAllCode(typeof(ApplicationTypeEnum));
        await base.OnParametersSetAsync();
    }
    /// <summary>
    /// 页面呈现后
    /// </summary>
    /// <param name="firstRender"></param>
    /// <returns></returns>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return;
        await InitDefaultDataInfoAsync();
        StateHasChanged();
        await base.OnAfterRenderAsync(true);
    }
    #endregion
    #region 事件
    /// <summary>
    /// 数据更改
    /// </summary>
    /// <param name="eventArgs"></param>
    public void OnDataChanged(ChangeEventArgs eventArgs)
    {
        FormData.Data.Value = eventArgs.Value.ToString();
    }
    /// <summary>
    /// 单击保存按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    public async Task OnBtnSaveClickAsync(MouseEventArgs eventArgs)
    {
        if (DefaultDataID.HasValue)
        {
            await EditDefaultDataAsync();
        }
        else
        {
            await AddDefaultDataAsync();
        }
    }
    /// <summary>
    /// 单击取消按钮
    /// </summary>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    public async Task OnBtnCancelClickAsync(MouseEventArgs eventArgs)
    {
        await Cancel.InvokeAsync(null);
    }
    #endregion
    #region 私有方法
    /// <summary>
    /// 初始化默认数据信息
    /// </summary>
    /// <returns></returns>
    private async Task InitDefaultDataInfoAsync()
    {
        if (_upInitDefaultDataID.HasValue && _upInitDefaultDataID == DefaultDataID) return;
        _upInitDefaultDataID = DefaultDataID;
        if (DefaultDataID.HasValue)
        {
            await InitOldDefaultDataInfoAsync(DefaultDataID.Value);
        }
        else
        {
            InitNewDefaultDataInfo();
        }
    }
    /// <summary>
    /// 初始化新默认数据
    /// </summary>
    /// <returns></returns>
    private void InitNewDefaultDataInfo()
    {
        Loading = true;
        FormData.Key.Value = string.Empty;
        FormData.Data.Value = string.Empty;
        FormData.ApplicationType = AllApplicationTypes.FirstOrDefault();
        Loading = false;
    }
    /// <summary>
    /// 初始化老默认数据
    /// </summary>
    /// <param name="defaultDataID"></param>
    /// <returns></returns>
    private async Task InitOldDefaultDataInfoAsync(Guid defaultDataID)
    {
        Loading = true;
        try
        {
            ResultModel<DefaultDataDTO> resultModel = await _defaultDataManage.GetInfoAsync(defaultDataID);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                InitOldDefaultDataInfo(resultModel.Data);
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 初始化老默认数据
    /// </summary>
    /// <param name="defaultDataInfo"></param>
    /// <returns></returns>
    private void InitOldDefaultDataInfo(DefaultDataDTO defaultDataInfo)
    {
        FormData.Key.Value = defaultDataInfo.Key;
        FormData.Data.Value = defaultDataInfo.Data;
        FormData.ApplicationType.ChangeByEnum(defaultDataInfo.ApplicationType);
    }
    /// <summary>
    /// 新增默认数据
    /// </summary>
    /// <returns></returns>
    private async Task AddDefaultDataAsync()
    {
        if (!Form.ValidateData()) return;
        Loading = true;
        try
        {
            var requestModel = new AddDefaultDataRequestModel
            {
                Key = FormData.Key.Value,
                Data = FormData.Data.Value,
                ApplicationType = (ApplicationTypeEnum)FormData.ApplicationType.GetEnumValue()
            };
            ResultModel resultModel = await _defaultDataManage.AddAsync(requestModel);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await Success.InvokeAsync(null);
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    /// <summary>
    /// 修改默认数据
    /// </summary>
    /// <returns></returns>
    private async Task EditDefaultDataAsync()
    {
        if (!Form.ValidateData()) return;
        Loading = true;
        try
        {
            if (!DefaultDataID.HasValue) throw new WebAPPException("未识别唯一标识");
            var requestModel = new EditDefaultDataRequestModel
            {
                ID = DefaultDataID.Value,
                Key = FormData.Key.Value,
                Data = FormData.Data.Value,
                ApplicationType = (ApplicationTypeEnum)FormData.ApplicationType.GetEnumValue()
            };
            ResultModel resultModel = await _defaultDataManage.EditAsync(requestModel);
            if (resultModel.ResultType == ResultTypeEnum.Success)
            {
                await _messageManage.SuccessAsync(resultModel.Message);
                await Success.InvokeAsync(null);
            }
            else
            {
                await _messageManage.WarningAsync(resultModel.Message);
            }
        }
        catch (Exception exception)
        {
            await _exceptionManage.HandlerExceptionAsync(exception);
        }
        finally
        {
            Loading = false;
        }
    }
    #endregion
}